package com.mt.api.modules.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.mt.common.response.WebResponse;
import com.mt.common.response.WebResponseUtils;
import com.mt.api.constants.constant.Constants;
import com.mt.api.constants.enums.CustomerBillTypeEnum;
import com.mt.api.constants.enums.OrderBackStatusEnum;
import com.mt.api.constants.enums.OrderStatusEnum;
import com.mt.api.constants.enums.OrderTypeEnum;
import com.mt.api.modules.domain.*;
import com.mt.api.modules.domain.bo.AppOrderAddBo;
import com.mt.api.modules.domain.bo.AppOrderDetailAddBo;
import com.mt.api.modules.domain.bo.AppOrderDetailSkuAddBo;
import com.mt.api.modules.domain.bo.AppOrderFinishBo;
import com.mt.api.modules.manager.*;
import com.mt.api.modules.mapper.AppOrderMapper;
import com.mt.api.modules.service.AppOrderBackService;
import com.mt.api.util.AmountUtil;
import com.mt.api.util.SequenceBuilder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author plover
 * @description 服务实现
 * @date 2020-07-06
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class AppOrderBackServiceImpl extends ServiceImpl<AppOrderMapper, AppOrder> implements AppOrderBackService {

    private final AppOrderDetailServiceImpl orderDetailService;
    private final ICustomerManager customerManager;
    private final ISkuManager skuManager;
    private final IStockManager stockManager;
    private final IOrderManager orderManager;
    private final IOrderDetailManager orderDetailManager;
    private final ICustomerBillManager customerBillManager;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public WebResponse backOrderAdd(AppOrderAddBo orderAddBo) {
        Integer customerId = orderAddBo.getCustomerId();
        AppCustomer customer = customerManager.getById(customerId);
        if (Objects.isNull(customer)) {
            return WebResponseUtils.error("客户不存在，请先新增客户");
        }

        List<AppOrderDetailAddBo> detailAddBoList = orderAddBo.getOrderDetailData();
        if (CollectionUtils.isEmpty(detailAddBoList)) {
            return WebResponseUtils.error("退货单明细不能为空");
        }
        SequenceBuilder builder = new SequenceBuilder();
        //配货单主表
        AppOrder appOrder = new AppOrder();
        appOrder.setOrderNo(builder.builderOrderBackNo());
        appOrder.setOrderTime(new Date());
        appOrder.setRarea(customer.getRarea());
        appOrder.setRaddress(customer.getRaddress());
        appOrder.setReceiver(customer.getReceiver());
        appOrder.setRphone(customer.getRphone());
        appOrder.setStatus(OrderBackStatusEnum.BACKED.getCode());
        appOrder.setType(OrderTypeEnum.BACK.getCode());
        appOrder.setRemark(orderAddBo.getRemark());
        appOrder.setCustomerId(customerId);
        appOrder.setShippingAddress(orderAddBo.getShippingAddress());
        appOrder.setSettleAmount(AmountUtil.multiplyHundred(orderAddBo.getSettleAmount()));
        appOrder.setFinishTime(new Date());
        baseMapper.insert(appOrder);

        AtomicInteger totalQty = new AtomicInteger(0);
        StringBuilder thing2Str = new StringBuilder();

        //配货单明细表
        List<AppOrderDetail> orderDetails = Lists.newArrayList();
        for (AppOrderDetailAddBo appOrderDetailAddBo : detailAddBoList) {
            List<AppOrderDetailSkuAddBo> skuInfoList = appOrderDetailAddBo.getSkuInfoList();
            for (AppOrderDetailSkuAddBo detailSkuAddBo : skuInfoList) {
                if (Objects.isNull(detailSkuAddBo.getSkuId()) || Objects.isNull(detailSkuAddBo.getQty()) || detailSkuAddBo.getQty() == 0) {
                    continue;
                }
                Integer skuId = detailSkuAddBo.getSkuId();
                AppSku sku = skuManager.getSkuById(skuId);
                if (Objects.isNull(sku)) {
                    continue;
                }
                AppOrderDetail appOrderDetail = new AppOrderDetail();
                appOrderDetail.setOrderId(appOrder.getId());
                appOrderDetail.setSkuId(sku.getId());
                appOrderDetail.setSkuCode(sku.getSkuCode());
                appOrderDetail.setCargoId(sku.getCargoId());
                appOrderDetail.setCargoNo(sku.getCargoNo());
                appOrderDetail.setColor(sku.getColor());
                appOrderDetail.setSize(sku.getSize());
                appOrderDetail.setQty(detailSkuAddBo.getQty());
                appOrderDetail.setPrice(AmountUtil.multiplyHundred(appOrderDetailAddBo.getWholesalePrice()));
                appOrderDetail.setAmount(detailSkuAddBo.getQty() * AmountUtil.multiplyHundred(appOrderDetailAddBo.getWholesalePrice()));
                orderDetails.add(appOrderDetail);
                totalQty.getAndAdd(detailSkuAddBo.getQty());
                thing2Str.append(sku.getCargoNo()).append("-").append(sku.getColor()).append("-")
                        .append(sku.getSize()).append("-").append(detailSkuAddBo.getQty()).append("件").append(";");
            }
        }
        //保存订单明细
        orderDetailService.saveBatch(orderDetails);
        //更新订单数量和金额
        int totalAmount = orderDetails.stream().mapToInt(AppOrderDetail::getAmount).sum();
        AppOrder order = new AppOrder();
        order.setId(appOrder.getId());
        order.setQty(totalQty.get());
        order.setAmount(totalAmount);
        if (order.getAmount() == AmountUtil.multiplyHundred(orderAddBo.getSettleAmount())) {
            appOrder.setSettleStatus(Constants.SettleStatus.SETTLE_FINISH);
        } else {
            appOrder.setSettleStatus(Constants.SettleStatus.UN_SETTLE);
        }
        orderManager.updateById(order);

        //保存客户账单
        AppCustomerBill customerBill = new AppCustomerBill();
        customerBill.setCustomerId(customerId);
        customerBill.setBusinessId(order.getId());
        customerBill.setType(CustomerBillTypeEnum.BACK.getCode());
        customerBill.setSettleAmount(Math.abs(totalAmount));
        customerBillManager.save(customerBill);

        //按照sku更新库存
        for (AppOrderDetailAddBo appOrderDetailAddBo : detailAddBoList) {
            List<AppOrderDetailSkuAddBo> skuInfoList = appOrderDetailAddBo.getSkuInfoList();
            for (AppOrderDetailSkuAddBo detailSkuAddBo : skuInfoList) {
                if (Objects.isNull(detailSkuAddBo.getSkuId()) || Objects.isNull(detailSkuAddBo.getQty()) || detailSkuAddBo.getQty() == 0) {
                    continue;
                }
                Integer qty = detailSkuAddBo.getQty();
                Integer skuId = detailSkuAddBo.getSkuId();
                AppSku sku = skuManager.getSkuById(skuId);
                if (Objects.isNull(sku)) {
                    continue;
                }
                //更新库存
                AppStock appStock = AppStock.builder().skuCode(sku.getSkuCode()).skuId(skuId)
                        .cargoNo(sku.getCargoNo()).cargoId(sku.getCargoId()).color(sku.getColor()).size(sku.getSize()).qty(qty).totalQty(qty)
                        .build();
                stockManager.saveOrUpdateStock(appStock);
            }
        }
        return WebResponseUtils.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public WebResponse cancelBackOrder(AppOrderFinishBo orderFinishBo) {
        AppOrder order = baseMapper.selectById(orderFinishBo.getId());
        if (Objects.isNull(order)) {
            return WebResponseUtils.error("销售退货单不存在");
        }
        if (order.getStatus() == OrderStatusEnum.CANCEL.getCode()) {
            return WebResponseUtils.error("销售退货单已撤销，不可重复撤销");
        }

        AppOrder appOrder = new AppOrder();
        appOrder.setId(orderFinishBo.getId());
        appOrder.setFinishTime(new Date());
        appOrder.setStatus(OrderStatusEnum.CANCEL.getCode());
        baseMapper.updateById(appOrder);

        // List<OutStore> outStoreList = outStoreManager.getListByOrderId(orderFinishBo.getId());
        // for (OutStore outStore : outStoreList) {
        //     OutStore upOutStore = new OutStore();
        //     upOutStore.setId(outStore.getId());
        //     upOutStore.setStatus(OutStoreStatusEnum.CANCEL.getCode());
        //     outStoreManager.updateById(upOutStore);
        // }
        List<AppOrderDetail> orderDetailList = orderDetailManager.getOrderDetailByOrderId(orderFinishBo.getId());
        for (AppOrderDetail appOrderDetail : orderDetailList) {
            AppSku sku = skuManager.getSkuById(appOrderDetail.getSkuId());
            if (Objects.isNull(sku)) {
                continue;
            }
            //退回单撤销，则将相应的库存扣除
            stockManager.subtractQtyBySkuId(sku.getId(), appOrderDetail.getQty());
        }

        AppCustomerBill customerBill = customerBillManager.getByBusinessIdAndType(order.getId(), CustomerBillTypeEnum.BACK.getCode());
        if (Objects.nonNull(customerBill)) {
            customerBillManager.removeById(customerBill.getId());
        }
        return WebResponseUtils.success();
    }

}